<template>
  <el-dialog
    v-el-drag-dialog
    class="dialog"
    :title="edittitle"
    :visible.sync="editor"
    :before-close="handleClose"
    :close-on-click-modal="false"
    width="520px"
  >
    <div class="dialog-content">
      <el-form
        ref="userFormData"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
        label-position="left"
        size="mini"
        :show-message="false"
        :hide-required-asterisk="true"
        :status-icon="false"
      >
        <el-form-item :label="$t('登录名称')" size="medium" prop="username">
          <el-input
            v-model="userForm.username"
            autocomplete="off"
            :show-word-limit="false"
            maxlength="20"
            clearable
            :disabled="!isAdd"
            @input="handleInputChange"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('登录密码')" size="medium" prop="password">
          <el-input
            v-model="userForm.password"
            autocomplete="off"
            :show-word-limit="false"
            maxlength="20"
            clearable
            show-password
            :disabled="!isAdd"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('用户昵称')" size="medium" prop="nickname">
          <el-input
            v-model="userForm.nickname"
            autocomplete="off"
            :show-word-limit="false"
            maxlength="20"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('手机号码')" size="medium" prop="phone">
          <el-input
            v-model="userForm.phone"
            autocomplete="off"
            :show-word-limit="false"
            maxlength="11"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('电子邮箱')" size="medium" prop="email">
          <el-input
            v-model="userForm.email"
            autocomplete="off"
            :show-word-limit="false"
            maxlength="30"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('角色权限')" size="medium">
          <el-select
            v-model="userForm.roleId"
            clearable
            :disabled="userForm.owner"
            :placeholder="$t('[未指定角色]')"
          >
            <el-option
              v-for="item in rolePermissions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('分配终端')" size="medium">
          <el-select-tree
            :placeholder="$t('[未分配终端组]')"
            :data="deviceList"
            :props="deviceProps"
            :disabled="userForm.owner"
            v-model="userForm.screenId"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            :default-expand-all="defaultExpandAll"
            :multiple="true"
          ></el-select-tree>
        </el-form-item>
        <el-form-item :label="$t('用户资源')" size="medium">
          <el-select
            v-model="possessionId"
            multiple
            :disabled="userForm.owner"
            :collapse-tags="true"
            :placeholder="$t('[沒有额外分配]')"
          >
            <el-option
              v-for="item in resourceList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('用户小组')" size="medium">
          <el-select-tree
            :placeholder="$t('[未指定用户组]')"
            :data="userGroupList"
            :props="groupProps"
            :disabled="userForm.owner"
            v-model="userForm.groupId"
            :check-strictly="checkStrictly"
            :default-expand-all="defaultExpandAll"
            :clearable="clearable"
          ></el-select-tree>
        </el-form-item>
        <el-form-item :label="$t('所属上级')" size="medium">
          <el-select-tree
            ref="uplevelTree"
            :placeholder="$t('[未分配所属上级]')"
            :data="userLevelList"
            :props="uplevelProps"
            :disabled="userForm.owner"
            v-model="userForm.parentId"
            :check-strictly="checkStrictly"
            :default-expand-all="defaultExpandAll"
            :disabled-values="disabledValues"
            :clearable="clearable"
            @change="clearParentId"
          ></el-select-tree>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onHandleConfirm">{{
        $t('确定')
      }}</el-button>
      <el-button @click="onHandleClose">{{ $t('取消') }}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import elDragDialog from '@/directive/el-drag-dialog'
// import ElSelectTree from 'el-select-tree'
import ScreenApi from '@/api/screen'
import crypto from 'crypto'
import { deepClone } from '@/utils/index'
export default {
  name: 'UserEditDialog',
  components: {},
  data() {
    return {
      edittitle: this.$t('用户编辑 - 新建用户'),
      activeName: 'first',
      editor: false,
      checkStrictly: true,
      clearable: true,
      defaultExpandAll: true,
      groupProps: {
        value: 'id',
        label: 'name',
        children: 'sysUserGroup',
      },
      deviceProps: {
        value: 'groupScreen',
        label: 'name',
        children: 'children',
        disabled: (data, node) => {
          if (data.type != 3) {
            return true
          } else {
            return false
          }
        },
      },
      disabledValues: [],
      uplevelProps: {
        value: 'id',
        label: 'username',
        children: 'childUser',
      },
      rolePermissions: [],
      deviceList: [],
      resourceList: [],
      userGroupList: [],
      userLevelList: [],
      userForm: {
        username: '',
        password: '',
        nickname: '',
        phone: '',
        email: '',
        roleId: 0,
        terminaGrouplId: 0,
        poss: [],
        groupId: 0,
        parentId: 0,
        screenId: [],
        shareTags: 0,
        id:0,
      },
      possessionId: [],
      deviceScreens: [],
      userFormRules: {
        username: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur',
          },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符' },
          {
            pattern: /^[A-Za-z\u4e00-\u9fa5]+$/,
            message: '名称只支持中英文组合且不能为空',
          },
        ],
        password: [
          {
            required: false,
            trigger: 'blur',
          },
          {
            min: 6,
            max: 15,
            message: '密码请输入6-15位任意字符',
          },
          // {
          //   pattern: /[0-9a-zA-Z]+$/,
          //   message: '密码请输入6-15位大小写字母、数字或数字加字母的形式',
          // },
        ],
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur',
          },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符' },
          {
            pattern: /^[A-Za-z\u4e00-\u9fa5]+$/,
            message: '昵称只能为中英文',
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入正确格式的手机号',
            trigger: 'blur',
          },
          { max: 11, message: '请输入正确格式的手机号' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
            message: '请输入正确格式的手机号',
          },
        ],
        email: [
          {
            required: false,
            trigger: 'blur',
          },
          { max: 30, message: '请输入正确格式的邮箱' },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '请输入正确格式的邮箱',
          },
        ],
      },
      input: '',
      isAdd: true,
      groupId: 0,
    }
  },
  created() {
    this.$eventBus.$on('userAddShow', this.show)
    this.$eventBus.$on('loadUserList', this.loadUserList)
  },
  beforeDestroy() {
    this.$eventBus.$off('userAddShow')
    this.$eventBus.$off('loadUserList')
  },
  directives: {
    elDragDialog,
  },
  methods: {
    clearParentId(a, b){
      if(!a && a !== 0) {
        this.$set(this.userForm, 'parentId', 0)
      }
    },
    //更新当前选中节点 获取groupid
    loadUserList(node) {
      this.groupId = node.id
    },
    // 终端节点点击事件
    nodeClick(data, node, obj) {
      if (data) {
        this.valueId = data.id
        this.$set(this.userForm, 'groupId', this.valueId)
      } else {
        this.valueId = ''
        this.$delete(this.userForm, 'groupId')
      }
    },
    // 显示
    show(form, isadd) {
      this.editor = true
      if (isadd) {
        this.resetForm()
        this.edittitle = this.$t('新建用户')
      } else {
        this.edittitle = this.$t('用户编辑')
        this.userForm = {
          ...form,
        }
        if (form.screenId) {
          this.deviceScreens = form.screenId
          const screenids = this.restoreScreenId(form.screenId)
          this.userForm.screenId = screenids
        }
        if (form.poss) {
          const possIds = this.resolvePossId(form.poss)
          this.possessionId = possIds
          console.log('userForm.possessionId------', this.possessionId)
        }
        this.userForm.userId = form.id
        this.disabledValues = [`${this.userForm.userId}`]
      }
      this.isAdd = isadd
      this.loadUserOrg()
      this.loadUserDevices()
      this.loadUserRoleList()
      this.loadUserResource()
      this.loadUserGroupList()
    },
    resetForm() {
      this.userForm = {
        username: '',
        password: '',
        nickname: '',
        phone: '',
        email: '',
        roleId: '',
        terminaGrouplId: 0,
        poss: [],

        groupId: 0,
        parentId: 0,
        screenId: [],
        shareTags: 0,
        id:0,
      }
      this.possessionId = []
      this.deviceScreens = []
    },
    //按钮确定
    onHandleConfirm() {
      this.$refs.userFormData.clearValidate()
      this.$refs.userFormData.validate(async (valid) => {
        if (valid) {
          if (this.isAdd) {
            this.addUser()
          } else {
            this.updateUser()
          }
        } else {
          let index = 0
          this.$refs.userFormData.fields.forEach((field) => {
            if (field.validateMessage) {
              if (index === 0) {
                this.$message.error(field.validateMessage)
                this.validateMsg = []
              }
              index++
            }
          })
          return
        }
      })
    },
    //按钮取消
    onHandleClose() {
      this.editor = false
      this.resetForm()
    },
    handleInputChange(val) {
      console.log('handleInputChange=' + val)
    },
    //dialog 所有关闭对话框都走
    handleClose(done) {
      console.log('handleClose')
      this.$refs.userFormData.clearValidate()
      this.$refs.userFormData.resetFields()
      done()
    },
    //获取组织架构（分配所属上级）
    loadUserOrg() {
      let params = {}
      this.$store.dispatch('system/loadUserUplevel', params).then((res) => {
        if (res) {
          this.userLevelList = res
        }
      })
    },
    //获取用户终端（分配终端）
    async loadUserDevices() {
      let params = {}
      const res = await ScreenApi.loadScreenTree()
      if (res) {
        this.deviceList = res
        // this.deviceScreens.forEach((element) => {
        //   let index = this.deviceList.findIndex(
        //     (item) => item.id === element.groupId
        //   )
        //   if (index === -1) {
        //     if (element.childrenId) {
        //       element.childrenId.forEach((screen) => {
        //         let devScreen = {}
        //         devScreen.groupScreen = element.groupId + '#' + screen.screenId
        //         devScreen.name = screen.screenName
        //         this.userForm.screenId.push(devScreen.groupScreen)
        //         // console.log('loadUserDevices----------',this.userForm.screenId)
        //         this.deviceList.push(devScreen)
        //         console.log('loadUserDevices--------push--',this.deviceList)
        //       })
        //     }
        //   }
        // })
      }
    },
    //用户角色列表
    loadUserRoleList() {
      let param = {
        userId:this.userForm.id
      }
      this.$store.dispatch('system/loadUserRoleList', param).then((res) => {
        this.rolePermissions = res
      })
    },
    //用户角色资源
    loadUserResource() {
      let params = {}
      this.$store.dispatch('system/loadUserResource', params).then((res) => {
        if (res) {
          this.resourceList = res
          if (this.userForm.poss) {
            this.userForm.poss.forEach((element) => {
              let index = this.resourceList.findIndex(
                (item) => item.id === element.id
              )
              if (index == -1) {
                this.resourceList.push(element)
              }
            })
          }
        }
      })
    },
    //用户小组
    loadUserGroupList() {
      let params = {}
      this.$store.dispatch('system/loadUserGroupList', params).then((res) => {
        this.userGroupList = res
      })
    },
    //新增用户
    addUser() {
      // if (!valitPassword(this.userForm.password)) {
      //   this.$alert(this.$t('提示'), this.$t('密码请输入6-15位大小写字母、数字或数字加字母的形式'))
      //   return
      // }
      const formData = deepClone(this.userForm)
      if (formData.screenId) {
        const screenIds = this.resolveScreenId(formData.screenId)
        formData.screenId = screenIds
      }

      var md5 = crypto.createHash('md5')
      md5.update(formData.password) //需要加密的密码
      var password = md5.digest('hex') //password 加密完的密码
      formData.password = password
      formData.possessionId = this.possessionId
      this.$store.dispatch('system/saveUser', formData).then((res) => {
        this.$success('add')
        this.$emit('do-refresh')
        this.editor = false
        
      })
    },
    updateUser() {
      const formData = deepClone(this.userForm)
      if (formData.screenId) {
        const screenIds = this.resolveScreenId(formData.screenId)
        formData.screenId = screenIds
      }
      formData.possessionId = this.possessionId
      this.$store.dispatch('system/updateUser', formData).then((res) => {
        this.$success('upd')
        this.$emit('do-refresh')
        this.editor = false
        
      })
    },
    resolveScreenId(array) {
      let screens = []
      let screenGroups = []
      array.forEach((element) => {
        const [groupid, screenId] = element.split('#')
        var screen = { groupId: groupid, screenId: screenId }
        screens.push(screen)
      })
      console.log('screens  ---------', screens)
      screens.forEach((element) => {
        if (screenGroups.some((ele) => ele.groupId == element.groupId)) {
          let group = screenGroups.find((ele) => {
            return ele.groupId == element.groupId
          })
          group.childrenId.push(Number(element.screenId))
        } else {
          screenGroups.push({
            groupId: Number(element.groupId),
            childrenId: [Number(element.screenId)],
          })
        }
      })
      console.log('screen ids ---------', screenGroups)
      return [...new Set(screenGroups)]
    },
    restoreScreenId(array) {
      let screenGroups = []
      console.log('restoreScreenId  ---------', array)
      array.forEach((element) => {
        if (element.childrenId) {
          const id = element.groupId
          element.childrenId.forEach((ele) => {
            screenGroups.push(id + '#' + ele.screenId)
          })
        }
      })
      console.log('screens  ---------', screenGroups)
      return [...new Set(screenGroups)]
    },
    resolvePossId(array) {
      let ids = []
      array.forEach((element) => {
        ids.push(element.id)
      })
      return [...new Set(ids)]
    },
  },
}
function getTreeData(data) {
  // 循环遍历json数据
  for (var i = 0; i < data.length; i++) {
    if (data[i].sysUserGroup.length < 1) {
      // children若为空数组，则将children设为undefined
      data[i].sysUserGroup = undefined
    } else {
      // children若不为空数组，则继续 递归调用 本方法
      getTreeData(data[i].sysUserGroup)
    }
  }
  return data
}
function getLevelData(data) {
  // 循环遍历json数据
  for (var i = 0; i < data.length; i++) {
    if (data[i].sysUserDTO.length < 1) {
      // children若为空数组，则将children设为undefined
      data[i].sysUserDTO = undefined
    } else {
      // children若不为空数组，则继续 递归调用 本方法
      getTreeData(data[i].sysUserGroup)
    }
  }
  return data
}
function valitName(name) {
  var reg = /^[\u0391-\uFFE5A-Za-z]+$/
  if (reg.test(name)) {
    return true
  } else {
    return false
  }
}
function valitPassword(pwd) {
  var reg = /[0-9a-zA-Z]{6,15}/
  if (reg.test(pwd)) {
    return true
  } else {
    return false
  }
}
function valitEmai(email) {
  var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (email != '' && regEmail.test(email)) {
    return true
  } else {
    return false
  }
}
function valitPhone(phone) {
  let reg = /^1[3|4|5|7|8][0-9]{9}$/
  if (phone != '' && reg.test(phone)) {
    return true
  } else {
    return false
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.dialog {
  ::v-deep .el-dialog__body {
    padding: 0 !important;
  }
  ::v-deep .el-dialog__footer {
    padding-top: 20px;
  }
}

.dialog-content {
  padding: 20px 30px 10px 30px;
}
.el-dialog__footer {
  text-align: center;
}
.el-form-item {
  margin-bottom: 14px;
}
.el-select {
  width: 100%;
}
.el-cascader {
  width: 100%;
}
.el-select-tree {
  width: 100%;
}
.el-form {
  background: #ffffff;
}
.el-button {
  margin-left: 10px !important;
}
</style>